package com.cgbl.cg.vm.login

import android.app.Application
import android.text.TextUtils
import androidx.databinding.ObservableField
import api.UserServiceFactory
import com.blankj.utilcode.util.StringUtils
import com.cgbl.cg.R
import com.cgbl.cg.im.ImManager
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractSpaceSubscriber
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.configs.PrefsManager
import com.robot.base.model.LoginBean
import com.robot.base.model.UserInfoBean
import com.robot.base.util.StringUtil
import com.robot.base.util.ToastUtils
import com.robot.base.util.arouter.ARouterUtil
import com.umeng.socialize.bean.SHARE_MEDIA
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class LoginPasswordViewModel(application: Application) : GLBaseViewModel(application) {

    val phone = ObservableField<String>()
    val password = ObservableField<String>()
    val phoneSelect = ObservableField(false)
    val phoneError = ObservableField("")
    val passwordSelect = ObservableField(false)
    val passwordError = ObservableField("")

    val promptSelect = ObservableField(false)

    val toLoginType = SingleLiveEvent<SHARE_MEDIA>()


    val toForgotPasswordCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(AppConstants.Router.Login.A_LOGIN_FORGOT_PASSWORD)
    })

    val doLoginCommand = BindingCommand<Any>(BindingAction {
        doLogin()
    })

    val promptClick = BindingCommand<Any>(BindingAction {
        promptSelect.set(!promptSelect.get()!!)
    })


    val toQqClick = BindingCommand<Any>(BindingAction {
        if (checkPrompt()) return@BindingAction
        toLoginType.postValue(SHARE_MEDIA.QQ)
    })

    val toWxClick = BindingCommand<Any>(BindingAction {
        if (checkPrompt()) return@BindingAction
        toLoginType.postValue(SHARE_MEDIA.WEIXIN)
    })


    private fun doLogin() {
        phoneSelect.set(!StringUtil.checkPhone(phone.get()))
        if (!StringUtil.checkPhone(phone.get())) {
            phoneError.set("号码输入错误")
            return
        }
        passwordSelect.set(TextUtils.isEmpty(password.get()))
        if (TextUtils.isEmpty(password.get())) {
            passwordError.set("密码未填写")
            return
        }
        val params = mapOf("mobile" to phone.get(), "password" to password.get())
        showLoadingDialog()
        UserServiceFactory.passwordLogin(params).flatMap {
            PrefsManager.saveUserLoginInfo(it.data)
            PrefsManager.loginSuccess()
            return@flatMap UserServiceFactory.userInfo()
        }.subscribe(object : AbstractViewModelSubscriber<BaseResponse<UserInfoBean>>(this) {
            override fun onNext(t: BaseResponse<UserInfoBean>) {
                dismissLoadingDialog()
                PrefsManager.saveUserInfo(t.data)
                val account = PrefsManager.getUserInfo().accid;
                val imToken = PrefsManager.getUserInfo().imToken
                ImManager.startLogin(account, imToken, object : ImManager.LoginListener {
                    override fun loginSuccess() {
                        ARouterUtil.goToActivity(AppConstants.Router.Main.A_MAIN)
                        finish()
                    }

                    override fun loginFailed() {
                        ToastUtils.showShort("登录IM系统失败!")
                    }
                })
            }
        })
    }

    private fun checkPrompt(): Boolean {
        if (promptSelect.get() == false) {
            ToastUtils.showShort(StringUtils.getString(R.string.app_error_4))
        }
        return promptSelect.get() == false
    }
}